from flask import flash, redirect, request, url_for
from flask_admin import BaseView, expose
from flask_login import current_user

from app.server.flask_app import db
from app.server.flask_app.forms.auth import UploadForm


# Заменить на form validate
class SettingsModelView(BaseView):
    @expose("/", methods=["GET", "POST"])
    def index(self):
        upload_form = UploadForm()

        if not current_user.is_authenticated:
            return redirect(url_for("auth_bp.login", next=request.url))

        if request.method == "GET":
            return self.render(
                "myadmin3/settings.html",
                upload_form=upload_form,
            )
        else:
            data = request.form
            current_user.first_name = data.get("first_name")
            current_user.last_name = data.get("last_name")
            current_user.nick_name = data.get("nick_name")
            current_user.location = data.get("location")
            current_user.website = data.get("website")
            current_user.bio = data.get("bio")
            db.session.commit()
            return redirect(url_for("profile.index"))

    @expose("/set-password", methods=["POST"])
    def set_password(self):
        data = request.form
        if current_user.validate_password(data.get("old_password")):
            current_user.set_password(data.get("password"))
            db.session.commit()
        else:
            flash("Old password is incorrect.", "warning")
        return redirect(url_for("profile.index"))
